package com.neusoft.neuiotms.dcam.common.repository.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcam.common.model.Location;
import com.neusoft.neuiotms.dcam.common.model.QLocation;
import com.neusoft.neuiotms.dcam.common.repository.CustomizedLocationRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedLocationRepositoryImpl extends AbstractRepository
        implements CustomizedLocationRepository {

    @Override
    public Page<Location> search(final Pageable pageable, final Searchable searchable) {
        final QLocation qLocation = QLocation.location;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Location> query = this.query().selectFrom(qLocation);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return Location.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QLocation qLocation = QLocation.location;

        where.and(super.containsStr(qLocation.name, searchable, "name"));
        where.and(super.containsStr(qLocation.code, searchable, "code"));
        if (!StringUtils.isEmpty(searchable.getStrValue("parentCode"))) {
            where.and(super.equalsStr(qLocation.parent.code, searchable, "parentCode"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("parentId"))) {
            where.and(super.equalsLong(qLocation.parent.id, searchable, "parentId"));
        }
        return where;
    }

}
